package file_share

//分享
import (
	"crypto/aes"
	"crypto/cipher"
	"crypto/rand"
	"encoding/base64"
	"errors"
	"fmt"
	"gitlab.local/DO-module/new-filemanage-module/src/constant"
	"gitlab.local/DO-module/new-filemanage-module/src/core/network"
	"gitlab.local/DO-module/new-filemanage-module/src/core/nginx"
	"gitlab.local/DO-module/new-filemanage-module/src/core/tnasonline"
	"gitlab.local/TerraMaster/tos-modules/database"
	"gitlab.local/TerraMaster/tos-modules/database/sqlitemodel"
	//"gitlab.local/TerraMaster/tos-modules/network"
	//"gitlab.local/TerraMaster/tos-modules/nginx"
	//"gitlab.local/TerraMaster/tos-modules/tnasonline"
	"gopkg.in/ini.v1"
	"io"
	"net/url"
	"os"
	"strconv"
	"strings"
	"time"

	"github.com/gogf/gf/errors/gerror"
	"gitlab.local/golibrary/utils"
)

const shareSecretKey = "b148r4c0c99fdd9b4e192139321f5vc4" //不要改，改了不能向下兼容

type Share struct {
	dbGetter   database.DbGetter
	ng         nginx.PortGetter
	net        network.Networkset
	tnasOnline tnasonline.Ctl
}

type EditShare struct {
	Id            int     `json:"id"`
	BanDownload   bool    `json:"ban_download"`
	BanDelete     bool    `json:"ban_delete"`
	BanAdd        bool    `json:"ban_add"`
	Title         string  `json:"title"`
	StaTime       *string `json:"sta_time"`
	ExpTime       *string `json:"exp_time"`
	AllowVisitNum int     `json:"allow_visit_num"`
	Password      *string `json:"password"`
	CustomDomain  string  `json:"custom_domain"` //自定义域名
}

// ShareStatus 文件状态
type ShareStatus struct {
	DeviceName string `json:"device_name"` //设备名称
	IsStart    bool   `json:"is_start"`    //是否未开始
	IsExpires  bool   `json:"is_expires"`  //是否已过期
	IsEncrypt  bool   `json:"is_encrypt"`  //是否加密
	IsDownload bool   `json:"is_download"` //是否禁止下载
	IsVisit    bool   `json:"is_visit"`    //是否禁止访问
	IsClose    bool   `json:"is_close"`    //是否已关闭
	BanDelete  bool   `json:"ban_delete"`  //是否禁止删除
	BanAdd     bool   `json:"ban_add"`     //是否禁止添加
	Tag        string `json:"tag"`         //tag
}

// ShareData 分享文件前端数据
type ShareData struct {
	ID                int      `json:"id"`
	CloseStatus       bool     `json:"close_status"`        //关闭状态
	Paths             []string `json:"paths"`               //文件路径
	Title             string   `json:"title"`               //分享标题
	StaTime           string   `json:"sta_time"`            //开始时间
	ExpTime           string   `json:"exp_time"`            //到期时间
	Password          string   `json:"password"`            //提取密码
	BanDownload       bool     `json:"ban_download"`        //禁止下载
	BanDelete         bool     `json:"ban_delete"`          //禁止删除
	BanAdd            bool     `json:"ban_add"`             //禁止添加
	AllowVisitNum     int      `json:"allow_visit_num"`     //允许访问次数,-1为无限制
	LocalShareLink    string   `json:"local_share_link"`    //本地访问链接
	RemoteSharingLink []string `json:"remote_sharing_link"` //远程访问链接
	QueryString       string   `json:"query_string"`        //请求参数
	Tag               string   `json:"tag"`                 //tag
	ShareIsEmpty      bool     `json:"share_is_empty"`      //分享是否为空
	CustomDomain      string   `json:"custom_domain"`       //自定义域名
}

func New(dbGetter database.DbGetter,
	ng nginx.PortGetter,
	net network.Networkset,
	tnasOnline tnasonline.Ctl,
) *Share {

	return &Share{
		dbGetter:   dbGetter,
		ng:         ng,
		net:        net,
		tnasOnline: tnasOnline,
	}
}

// IsShare 判断用户是否有分享文件
func (r *Share) IsShare(userName, tag string) bool {
	var num int64

	_ = r.dbGetter.DbGet().Model(&sqlitemodel.ShareConfig{}).Where(`"user"=? and tag=?`, userName, tag).Count(&num)

	return num > 0
}

// GetShareList 获取分享列表
func (r *Share) GetShareList(userName, tag string, page, limit int) ([]ShareData, error) {
	if page > 1 {
		page = (page - 1) * limit
	}
	var data []sqlitemodel.ShareConfig
	db := r.dbGetter.DbGet().Where(`"user"=? and tag=?`, userName, tag)
	if page > 1 {
		db = db.Offset(page)
	}
	if limit > 0 {
		db = db.Limit(limit).Order("id desc")
	}
	_ = db.Find(&data)
	shareList := make([]ShareData, 0)
	for _, v := range data {
		msg, err := r.getShareMsg(v, r.GetCustomDomain())
		if err != nil {
			continue
		}
		msg.Password = ""
		msg.Tag = tag
		shareList = append(shareList, *msg)
	}

	return shareList, nil
}

// GetShareMsg 获取单个分享信息
func (r *Share) GetShareMsg(id int, ddnsDomain string) (*ShareData, error) {
	data, err := r.GetShareData(id)
	if err != nil {
		return nil, gerror.Wrap(err, "GetShareMsg")
	}

	return r.getShareMsg(*data, ddnsDomain)
}

// getShareMsg 获取分享信息
func (r *Share) getShareMsg(shareConfig sqlitemodel.ShareConfig, ddnsDomain string) (*ShareData, error) {
	var ids []int
	for _, val := range strings.Split(shareConfig.PathsId, ",") {
		atoi, err := strconv.Atoi(val)
		if err == nil {
			ids = append(ids, atoi)
		}
	}
	var res []sqlitemodel.SharePath
	sl := &ShareData{Paths: make([]string, 0)}
	if len(ids) > 0 {
		_ = r.dbGetter.DbGet().Where("id in ?", ids).Find(&res)
		sl.ShareIsEmpty = true
		for _, val := range res {
			if utils.Exists(val.Path) {
				sl.ShareIsEmpty = false
			}
			sl.Paths = append(sl.Paths, val.Path)
		}
	}
	sl.CloseStatus = shareConfig.CloseStatus
	sl.BanAdd = shareConfig.BanAdd
	sl.BanDownload = shareConfig.BanDownload
	sl.BanDelete = shareConfig.BanDelete
	sl.ID = shareConfig.Id
	sl.Title = shareConfig.Title
	sl.Password = shareConfig.Password
	sl.AllowVisitNum = shareConfig.AllowVisitNum
	sl.QueryString = r.requestQuery(shareConfig.ShareLink)
	sl.LocalShareLink = r.getLocalShareLink(sl.QueryString)
	sl.RemoteSharingLink = r.getRemoteSharingLink(sl.QueryString, ddnsDomain)
	sl.CustomDomain = ddnsDomain
	if !shareConfig.StaTime.IsZero() {
		sl.StaTime = shareConfig.StaTime.Format("2006-01-02 15:04:05")
	}
	if !shareConfig.ExpTime.IsZero() {
		sl.ExpTime = shareConfig.ExpTime.Format("2006-01-02 15:04:05")
	}

	return sl, nil
}

// getLocalShareLink 获取本地访问地址,优先使用https
func (r *Share) getLocalShareLink(requestQuery string) string {
	ip := r.net.GetIntranetIpv4()
	httpsPort, _ := r.ng.GetHttpsPort()
	if httpsPort > 0 {
		return fmt.Sprintf("https://%s:%d%s?%s", ip, httpsPort, constant.PageAddress, requestQuery)
	}
	httpPort, _ := r.ng.GetHttpPort()

	return fmt.Sprintf("http://%s:%d%s?%s", ip, httpPort, constant.PageAddress, requestQuery)
}

// getRemoteSharingLink 获取远程访问地址
func (r *Share) getRemoteSharingLink(requestQuery, ddnsDomain string) []string {
	data := make([]string, 0)

	if ddnsDomain != "" {
		data = append(data, fmt.Sprintf("%s%s?%s", ddnsDomain, constant.PageAddress, requestQuery))
	} else {
		//TNAS.online
		if r.tnasOnline.IsEnabled() {
			id, _ := r.tnasOnline.GetId()
			if id != "" {
				server, _ := r.tnasOnline.GetSelectedServer()
				if server != "" {
					data = append(data, fmt.Sprintf("https://%s.%s%s?%s", id, server, constant.PageAddress, requestQuery))
				} else {
					data = append(data, fmt.Sprintf("https://%s%s?%s", id, constant.PageAddress, requestQuery))
				}
			}
		}
	}

	return data
}

// requestQuery 访问请求参数
func (r *Share) requestQuery(shareLink string) string {
	return "share_link=" + shareLink
}

// IsSubPath 判断是否为子路径
// PathsId SharePath表id，逗号分隔
// subPath子路径集合,列:/etc/aa /etc/aa/bb.txt
func (r *Share) IsSubPath(PathsId string, subPath []string) bool {
	var arr []int
	for _, v := range strings.Split(PathsId, ",") {
		atoi, err := strconv.Atoi(v)
		if err == nil {
			arr = append(arr, atoi)
		}
	}
	if len(arr) == 0 {
		return false
	}
	var res []sqlitemodel.SharePath
	_ = r.dbGetter.DbGet().Where("id in ?", arr).Find(&res)
	for _, v := range res {
		for _, val := range subPath {
			if strings.HasPrefix(strings.TrimRight(val, "/")+"/", strings.TrimRight(v.Path, "/")+"/") {
				return true
			}
		}
	}

	return false
}

// GetShareData 获取单个文件分享配置信息(数据库数据)
func (r *Share) GetShareData(id int) (*sqlitemodel.ShareConfig, error) {
	data := &sqlitemodel.ShareConfig{}
	if err := r.dbGetter.DbGet().Where(`id=?`, id).First(data).Error; err != nil {
		return nil, gerror.Wrap(err, "GetShareData")
	}

	return data, nil
}

// ShareStatus 获取分享文件可操作状态
func (r *Share) ShareStatus(data *sqlitemodel.ShareConfig) *ShareStatus {
	DeviceName, _ := os.Hostname()
	now := time.Now()

	return &ShareStatus{
		DeviceName: DeviceName,
		IsStart:    !(data.StaTime.IsZero() || now.After(data.StaTime)),
		IsExpires:  !(data.ExpTime.IsZero() || now.Before(data.ExpTime)),
		IsEncrypt:  data.Password != "",
		IsDownload: data.BanDownload,
		IsVisit:    !(data.AllowVisitNum == -1 || data.AllowVisitNum > 0),
		IsClose:    data.CloseStatus,
		BanDelete:  data.BanDelete,
		BanAdd:     data.BanAdd,
		Tag:        data.Tag,
	}
}

// ParseShareLink 解析ShareLink信息
func (r *Share) ParseShareLink(shareLink string) (url.Values, error) {
	decrypt, err := r.Decrypt(shareLink)
	if err != nil {
		return nil, gerror.Wrap(err, "parseShareLink")
	}
	return url.ParseQuery(string(decrypt))
}

// VerifySharePwd 验证分享文件密码
// shareLink 请求参数（ShareLink分享链接参数path=%s&user=%s&time=%s）
// pwd 密码
// return 0失败，1成功，2分享被关闭，3未开始，4已过期，5禁止访问，6密码错误
func (r *Share) VerifySharePwd(shareLink, pwd string) (uint8, error) {
	unescape, err := url.PathUnescape(shareLink)
	if err != nil {
		return 0, gerror.Wrap(err, "VerifySharePwd11")
	}
	link, err := r.ParseShareLink(unescape)
	if err != nil {
		return 0, gerror.Wrap(err, "VerifySharePwd")
	}
	atoi, err := strconv.Atoi(link.Get("id"))
	if err != nil {
		return 0, gerror.Wrap(err, "VerifySharePwd1")
	}
	data, e := r.GetShareData(atoi)
	if e != nil {
		return 0, gerror.Wrap(e, "VerifySharePwd2")
	}
	status := r.ShareStatus(data)
	if status.IsClose {
		return 2, nil
	}
	if status.IsStart {
		return 3, nil
	}
	if status.IsExpires {
		return 4, nil
	}
	if status.IsVisit {
		return 5, nil
	}
	if r.VerifyPwd(data.Password, pwd) {
		return 1, nil
	}
	return 6, nil
}

// VerifyPwd 验证分享文件密码
// return false密码错误，true密码正确
func (r *Share) VerifyPwd(oldPwd, newPwd string) bool {
	return oldPwd == "" || oldPwd == newPwd
}

// AddShareFile 添加分享文件
func (r *Share) AddShareFile(userName, ddnsDomain string, data ShareData) (*ShareData, error) {
	db := r.dbGetter.DbGet()
	var ids []string
	for _, val := range data.Paths {
		if !utils.Exists(val) {
			return nil, errors.New(fmt.Sprintf(`[%s] nonentity`, val))
		}
		inData := sqlitemodel.SharePath{
			Path:       val,
			CreateData: time.Now(),
		}
		_ = db.Create(&inData)
		if inData.Id == 0 {
			_ = db.Where("path=?", val).Select("id").First(&inData)
		}
		ids = append(ids, strconv.Itoa(inData.Id))
	}
	var (
		staTime time.Time
		expTime time.Time
		err     error
	)
	if data.StaTime != "" {
		staTime, err = time.ParseInLocation("2006-01-02 15:04:05", data.StaTime, time.Local)
		if err != nil {
			return nil, gerror.Wrap(err, "Parse start time fail")
		}
	}
	if data.ExpTime != "" {
		expTime, err = time.ParseInLocation("2006-01-02 15:04:05", data.ExpTime, time.Local)
		if err != nil {
			return nil, gerror.Wrap(err, "Parse expire time fail")
		}
	}
	inData := sqlitemodel.ShareConfig{ //添加数据
		PathsId:          strings.Join(ids, ","),
		User:             userName,
		Title:            data.Title,
		StaTime:          staTime,
		ExpTime:          expTime,
		Password:         data.Password,
		BanDownload:      data.BanDownload,
		ShareLink:        "",
		AllowVisitNum:    data.AllowVisitNum,
		CreateData:       time.Now(),
		RemoteSharDomain: "",
		BanAdd:           data.BanAdd,
		BanDelete:        data.BanDelete,
		ViewCount:        0,
		DownloadCount:    0,
		CloseStatus:      data.CloseStatus,
		Tag:              data.Tag,
	}
	if err = db.Create(&inData).Error; err != nil {
		return nil, gerror.Wrap(err, "Create share fail")
	}
	shareLink, err := r.Encrypt([]byte(fmt.Sprintf("id=%d&user=%s", inData.Id, userName)))
	if err != nil {
		return nil, gerror.Wrap(err, "Encrypt share link fail")
	}
	err = db.Model(&sqlitemodel.ShareConfig{}).Where("id=?", inData.Id).Update("share_link", url.QueryEscape(shareLink)).Error
	if err != nil {
		return nil, gerror.Wrap(err, "Update share fail")
	}
	return r.GetShareMsg(inData.Id, ddnsDomain)
}

// Encrypt 加密
func (r *Share) Encrypt(data []byte) (string, error) {
	ciphertext, err := encrypt([]byte(shareSecretKey), data)
	if err != nil {
		return "", gerror.Wrap(err, "Encrypt")
	}
	return base64.StdEncoding.EncodeToString(ciphertext), nil
}

// encrypt
// @Description: 文件分享加密
// @param key
// @param plaintext
// @return []byte
// @return error
func encrypt(key, plaintext []byte) ([]byte, error) {
	block, err := aes.NewCipher(key)
	if err != nil {
		return nil, err
	}
	ciphertext := make([]byte, aes.BlockSize+len(plaintext))
	iv := ciphertext[:aes.BlockSize]
	if _, err := io.ReadFull(rand.Reader, iv); err != nil {
		return nil, err
	}

	stream := cipher.NewCFBEncrypter(block, iv)
	stream.XORKeyStream(ciphertext[aes.BlockSize:], plaintext)
	return ciphertext, nil
}

// Decrypt 解密
func (r *Share) Decrypt(str string) ([]byte, error) {
	decodeString, _ := base64.StdEncoding.DecodeString(str)
	decryptedText, err := decrypt([]byte(shareSecretKey), decodeString)
	if err != nil {
		return nil, gerror.Wrap(err, "Decrypt")
	}
	return decryptedText, nil
}

// decrypt
// @Description: 文件分享解密
// @param key
// @param ciphertext
// @return []byte
// @return error
func decrypt(key, ciphertext []byte) ([]byte, error) {
	block, err := aes.NewCipher(key)
	if err != nil {
		return nil, err
	}
	iv := ciphertext[:aes.BlockSize]
	ciphertext = ciphertext[aes.BlockSize:]
	plaintext := make([]byte, len(ciphertext))
	stream := cipher.NewCFBDecrypter(block, iv)
	stream.XORKeyStream(plaintext, ciphertext)
	return plaintext, nil
}

// IncreaseViewCount 增加浏览量,扣除可访问次数
func (r *Share) IncreaseViewCount(shareLink, pwd string) (bool, error) {
	link, err := r.ParseShareLink(shareLink)
	if err != nil {
		return false, gerror.Wrap(err, "IncreaseViewCount")
	}
	atoi, err := strconv.Atoi(link.Get("id"))
	if err != nil {
		return false, gerror.Wrap(err, "IncreaseViewCount1")
	}
	data, e := r.GetShareData(atoi)
	if e != nil {
		return false, gerror.Wrap(e, "IncreaseViewCount2")
	}
	if !r.VerifyPwd(data.Password, pwd) {
		return false, errors.New("wrong password")
	}
	//修改
	upDate := make(map[string]interface{})
	upDate["view_count"] = data.ViewCount + 1
	if data.AllowVisitNum > 0 {
		upDate["allow_visit_num"] = data.AllowVisitNum - 1
	}
	if e = r.dbGetter.DbGet().Model(&sqlitemodel.ShareConfig{}).Where("id=?", data.Id).Updates(upDate).Error; e != nil {
		return false, gerror.Wrap(e, "IncreaseViewCount3")
	}
	return true, nil
}

// UploadShareFileVerify 上传分享文件校验
func (r *Share) UploadShareFileVerify(shareLink, pwd string) (string, error) {
	link, err := r.ParseShareLink(shareLink) //解析参数
	if err != nil {
		return "", gerror.Wrap(err, "UploadShareFileVerify")
	}
	atoi, err := strconv.Atoi(link.Get("id"))
	if err != nil {
		return "", gerror.Wrap(err, "UploadShareFileVerify1")
	}
	data, err := r.GetShareData(atoi)
	if err != nil {
		return "", gerror.Wrap(err, "UploadShareFileVerify2")
	}
	if !r.VerifyPwd(data.Password, pwd) { //验证密码
		return "", errors.New("wrong password")
	}
	return link.Get("user"), nil
}

// DelShare 删除分享
func (r *Share) DelShare(id int) error {
	return r.dbGetter.DbGet().Where("id=?", id).Delete(&sqlitemodel.ShareConfig{}).Error
}

// AddShareLinkFileControl 添加分享链接中的分享文件(有权限控制)
func (r *Share) AddShareLinkFileControl(id int, paths []string) error {
	data, e := r.GetShareData(id)
	if e != nil {
		return gerror.Wrap(e, "AddOrDelShareLinkFile")
	}

	//是否允许添加
	if data.BanAdd {
		return errors.New("not allowed to add")
	}
	return r.addShareLinkFile(data, paths)
}

// DelShareLinkFileControl 删除分享链接中的分享文件(有权限控制)
func (r *Share) DelShareLinkFileControl(id int, paths []string) error {
	data, e := r.GetShareData(id)
	if e != nil {
		return gerror.Wrap(e, "AddOrDelShareLinkFile")
	}
	//是否允许删除
	if data.BanDelete {
		return errors.New("not allowed to delete")
	}
	return r.delShareLinkFile(data, paths)
}

// AddShareLinkFile 添加分享链接中的分享文件
func (r *Share) AddShareLinkFile(id int, paths []string) error {
	data, e := r.GetShareData(id)
	if e != nil {
		return gerror.Wrap(e, "AddOrDelShareLinkFile")
	}

	return r.addShareLinkFile(data, paths)
}

// DelShareLinkFile 删除分享链接中的分享文件
func (r *Share) DelShareLinkFile(id int, paths []string) error {
	data, e := r.GetShareData(id)
	if e != nil {
		return gerror.Wrap(e, "AddOrDelShareLinkFile")
	}

	return r.delShareLinkFile(data, paths)
}

func (r *Share) addShareLinkFile(data *sqlitemodel.ShareConfig, path []string) error {
	db := r.dbGetter.DbGet()
	var ids []string
	for _, v := range path {
		inData := sqlitemodel.SharePath{
			Path:       v,
			CreateData: time.Now(),
		}
		_ = db.Create(&inData)
		if inData.Id == 0 {
			_ = db.Where("path=?", v).Select("id").First(&inData)
		}
		ids = append(ids, strconv.Itoa(inData.Id))
	}
	ids = r.sliceMerging(strings.Split(data.PathsId, ","), ids)
	return db.Model(&sqlitemodel.ShareConfig{}).Where("id=?", data.Id).Update("paths_id", strings.Join(ids, ",")).Error
}

func (r *Share) delShareLinkFile(data *sqlitemodel.ShareConfig, path []string) error {
	var pathsId []string

	var res []sqlitemodel.SharePath
	db := r.dbGetter.DbGet()
	_ = db.Where("path in ?", path).Select("id").Find(&res)

	pathsIdMap := make(map[string]bool)

	// 预先处理res中每个Id的字符串表示，存储结果到map中。
	for _, val := range res {
		idStr := strconv.Itoa(val.Id)
		pathsIdMap[idStr] = true
	}

	// 只有不在map中的id会被添加到pathsId中。
	for _, v := range strings.Split(data.PathsId, ",") {
		if _, exists := pathsIdMap[v]; !exists {
			pathsId = append(pathsId, v)
		}
	}

	return db.Model(&sqlitemodel.ShareConfig{}).Where("id=?", data.Id).Update("paths_id", strings.Join(pathsId, ",")).Error
}

func (r *Share) sliceMerging(a []string, b []string) []string {
	data := make(map[string]bool)
	for _, v := range append(a, b...) {
		data[v] = false
	}
	var c []string
	for k := range data {
		c = append(c, k)
	}
	return c
}

// EditShare 编辑分享配置
func (r *Share) EditShare(arg *EditShare) error {
	data := map[string]interface{}{
		"ban_download": arg.BanDownload,
		"ban_delete":   arg.BanDelete,
		"ban_add":      arg.BanAdd,
	}
	if arg.Title != "" {
		data["title"] = arg.Title
	}

	if arg.StaTime != nil {
		if *arg.StaTime != "" {
			location, err := time.ParseInLocation("2006-01-02 15:04:05", *arg.StaTime, time.Local)
			if err != nil {
				return gerror.Wrap(err, "EditShare")
			}
			data["sta_time"] = location
		} else {
			data["sta_time"] = time.Time{}
		}
	}

	if arg.ExpTime != nil {
		if *arg.ExpTime != "" {
			location, err := time.ParseInLocation("2006-01-02 15:04:05", *arg.ExpTime, time.Local)
			if err != nil {
				return gerror.Wrap(err, "EditShare1")
			}
			data["exp_time"] = location
		} else {
			data["exp_time"] = time.Time{}
		}
	}

	if arg.Password != nil {
		if *arg.Password != "" {
			data["password"] = arg.Password
		} else {
			data["password"] = ""
		}
	}

	if arg.AllowVisitNum != 0 {
		data["allow_visit_num"] = arg.AllowVisitNum
	}

	if err := r.saveCustomDomain(arg.CustomDomain); err != nil {
		return gerror.Wrap(err, "EditShare2")
	}

	return r.dbGetter.DbGet().Model(&sqlitemodel.ShareConfig{}).Where("id=?", arg.Id).Updates(data).Error
}

func (r *Share) GetCustomDomain() string {
	load, err := ini.Load(constant.SysDefault)
	if err != nil {
		return ""
	}
	return load.Section("system").Key("share_custom_domain").Value()
}

func (r *Share) saveCustomDomain(customDomain string) error {
	if customDomain == "" {
		return nil
	}
	load, err := ini.Load(constant.SysDefault)
	if err != nil {
		return gerror.Wrap(err, "EditShare2")
	}
	load.Section("system").Key("share_custom_domain").SetValue(customDomain)
	if err = load.SaveTo(constant.SysDefault); err != nil {
		return gerror.Wrap(err, "EditShare3")
	}
	return nil
}

// SwitchCloseStatus 修改关闭状态
func (r *Share) SwitchCloseStatus(id int, status bool) error {
	return r.dbGetter.DbGet().Model(&sqlitemodel.ShareConfig{}).Where("id=?", id).Update("close_status", status).Error
}

// GetShareConfigPaths 获取某个分享链接的文件paths
func (r *Share) GetShareConfigPaths(shareConfigId int) []string {
	data := make([]string, 0)
	var res sqlitemodel.ShareConfig
	db := r.dbGetter.DbGet()
	_ = db.Where("id=?", shareConfigId).Select("paths_id").First(&res)
	if res.PathsId == "" {
		return data
	}
	var paths []sqlitemodel.SharePath
	_ = db.Where("id in ?", strings.Split(res.PathsId, ",")).Select("path").Find(&paths)
	for _, v := range paths {
		data = append(data, v.Path)
	}
	return data
}
